package com.aynu.gulimall.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author mj
 * @version 1.0
 * @date 2021/3/11 16:02
 */
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class MyCacheConfig {

//    @Autowired
//    CacheProperties cacheProperties;

    /**
     * 配置文件中的东西没用上,因为我们没有引入配置文件的配置,下面的设置加上的配置文件的配置
     *
     * 1、原来和配置文件绑定的配置类是这样的
     *  原来的获取配置文件是这样的：@ConfigurationProperties(prefix = "spring.cache")
     * 2、
     *  我们直接使用加上【@EnableConfigurationProperties(CacheProperties.class)】，把类加载进来
     *
     *  TODO 待解决:为什么能自动使用这个配置实例?
     *
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        //获取默认配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //指定key的序列化机制
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.
                fromSerializer(new StringRedisSerializer()));
        //指定value的序列化机制(json)
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.
                fromSerializer(new GenericFastJsonRedisSerializer()));

        //将配置文件中的所有配置也配置上
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }
}
